package main

import (
	"fmt"
	"github.com/micro/go-micro/client/selector"
	"github.com/micro/go-micro/registry"
	"github.com/micro/go-micro/registry/etcd"
	"github.com/micro/go-micro/web"
	"singo/conf"
	"singo/server"
	"time"
)

func main() {
	// 从配置文件读取配置
	conf.Init()

	// 装载路由
	r := server.NewRouter()
	//r.Run(":3000")

	//注册到etcd
	etc := etcd.NewRegistry(registry.Addrs("127.0.0.1:2379"),)

	//使用go-micro
	server1 := web.NewService(
		web.Name("apo.test.v1"),  //服务名称
		web.Address(":3000"),
		web.Handler(r),
		web.Registry(etc),  //注册到etcd
		)

	server1.Run()

}

// 获取服务地址
func GetServiceAddr(etcdReg  registry.Registry  ,serviceName string)(address string) {
	var retryCount int
	for {
		servers, err := etcdReg.GetService(serviceName)
		if err != nil {
			fmt.Println(err.Error())
		}
		var services []*registry.Service
		for _, value := range servers {
			fmt.Println(value.Name, ":", value.Version)
			services = append(services, value)
		}
		next := selector.RoundRobin(services)
		if node, err := next(); err == nil {
			address = node.Address
		}
		if len(address) > 0 {
			return
		}
		// 重试次数
		retryCount  ++
		time.Sleep(time.Second * 3)
		if retryCount >= 5 {
			return
		}
	}
}
